package com.seven.smartsnmp.discover.service;

import com.seven.smartsnmp.config.DiscoverConfig;
import com.seven.smartsnmp.discover.DeviceInfo;
import com.seven.smartsnmp.discover.DeviceTypeInfo;
import com.seven.smartsnmp.mib.MibSoftwareRunEntry;
import com.seven.smartsnmp.snmp.SNMPFactory;
import com.seven.smartsnmp.snmp.SNMPTarget;
import org.apache.commons.lang3.StringUtils;

import java.util.Iterator;
import java.util.List;

/**
 * @author Admin
 */
public class SearchTypeService {
    public SearchTypeService() {
    }

    /**
     * 匹配设备类型
     *
     * @param deviceInfo
     * @return
     */
    public DeviceTypeInfo matchDeviceType(DeviceInfo deviceInfo) {
        List nodeTypeList = DiscoverConfig.getAllDeviceType();
        Iterator it = nodeTypeList.iterator();
        DeviceTypeInfo deviceTypeInfo;
        while (it.hasNext()) {
            deviceTypeInfo = (DeviceTypeInfo) it.next();
            Iterator oidIt = deviceTypeInfo.getTypeOIDCharacter().iterator();
            while (oidIt.hasNext()) {
                String oid = (String) oidIt.next();
                if (StringUtils.isNotBlank(oid) && deviceInfo.getDeviceSysOID().contains(oid)) {
                    return deviceTypeInfo;
                }
            }
        }
        if (deviceInfo.getDeviceProtocol().equalsIgnoreCase("SNMP") && deviceInfo.getSnmpTarget() != null) {
            SNMPTarget snmpTarget = deviceInfo.getSnmpTarget();
            String type = null;
            String dot = null;
            try {
                type = SNMPFactory.getSNMPAPI().getOIDValue(".1.3.6.1.2.1.4.1.0", snmpTarget);
            } catch (Exception e) {
                System.out.println(deviceInfo.getDeviceIP() + "错误:" + e.getMessage());
            }
            try {
                dot = SNMPFactory.getSNMPAPI().getOIDValue(".1.3.6.1.2.1.17.2.1.0", snmpTarget);
            } catch (Exception e) {
                System.out.println(deviceInfo.getDeviceIP() + "错误:" + e.getMessage());
            }
            if (StringUtils.isNotBlank(dot)) {
                if (StringUtils.isNotBlank(type) && type.equals("1")) {
                    return DeviceTypeInfo.RouterSwitchType;
                }
                return DeviceTypeInfo.SwitchType;
            }
            if (StringUtils.isNotBlank(type) && type.equals("1")) {
                return DeviceTypeInfo.RouterType;
            }
            try {
                List softwareRunEntryList = SNMPFactory.getSNMPAPI().getAllTableData(MibSoftwareRunEntry.class, snmpTarget);
                if (softwareRunEntryList.size() > 0) {
                    return DeviceTypeInfo.ComputerType;
                }
            } catch (Exception e) {
                System.out.println(deviceInfo.getDeviceIP() + "错误:" + e.getMessage());
            }
        }
        return DeviceTypeInfo.UnkownType;
    }
}
